<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FormData</title>
</head>
<body>
        <form 
            id="login"
            action="https://www.imooc.com/api/http/search/suggest?words=js"
            method="POST"
            enctype="application/x-www-form-urlencoded"
        >
            <input type="text" name="username" placeholder="用户名">
            <input type="password" name="pwd" placeholder="密码">
            <input type="submit" value="登录">
        </form>
    
    <script>
        const login = document.querySelector('#login');
        const sub = document.querySelector('#login > input[type=submit]');

        const url = 'https://www.imooc.com/api/http/search/suggest?words=js';
        const {username,pwd} = login;

        sub.addEventListener('click',(e)=>{
            e.preventDefault();    // 阻止默认行为

            // 表单的数据验证
            // 略

            // 使用 Ajax 提交表单
            const xhr = new XMLHttpRequest();
            xhr.addEventListener('load',()=>{
                if((xhr.status >= 200 && xhr.status <300) || xhr.status === 304){
                    console.log(xhr.response);
                }
            })

            // 组装数据
            // const data = `username=${username}&pwd=${pwd}`;

            // 使用 FormData 组装数据
            const data = new FormData(login);
            // 添加数据
            data.append('age',18);
            /* for(let i of data){
                console.log(i);
            } */

            xhr.open('POST',url,true);

            // xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')

            xhr.send(data);


        })
        
    </script>
</body>
</html>